package com.atguigu.scala2.chapter4

import org.junit.Test

import scala.util.control.Breaks._

/**
 * @author lizikuan
 * @date 2021/7/12 19:59
 */
class Test1 {

  @Test
  def test1(): Unit ={
    val r = {
      println("------")
      val x = 1
      val y =2
      x+y
    }
    println(r)
  }

  //if条件
  @Test
  def test2(): Unit ={
    val a = 10
    //单分支
    val r  = if( a % 2 == 0 ){
      a
    }
    println(r)

  }

  //for循环
  @Test
  def test3(): Unit = {
    for (i <- 1 to 100) {
      if (i % 2 == 0) {
        println(i)
      }
    }
    println("------------------------------------------")

    //守卫
    for (i <- 1.to(100) by 3){
      println(i)
    }

    //99乘法表
    for(i <- 1 to 9){
      for (j <- 1.to(i)){
        print(s"i * j = ${i*j}  ")
      }
      println()
    }
  }

  //yield表达式，让for循环拥有返回值
  @Test
  def test4() = {
    val seq = for (i <- 10 to 100) yield {
      if (i % 2 != 0) {
        i
      }else{
        0
      }
    }
    val list = seq.toList
    println(list)
  }


  @Test
  def test5()={
    var a = 1
    while (a<=10){
      println(a)
      a.+=(1)
    }
    println("--------------------------")
    var b =2
    do{
      b += 1
      println(b)
    }while(b<=10)
  }


  @Test
  def test6() = {
    //用异常实现break
    try {
      for (i <- 1 to 10) {
        println(i)
        if (i==5) throw new Exception("i==5")
      }
    }catch {
      case e: Exception =>
    }
  }

  //用异常实现continue
  @Test
  def test7 = {

    for (i <- 1 to 10){
      try {
        if (i==6) throw new Exception
        println(i)
      }catch {
        case e:Exception =>
      }
    }
  }

  //用scala的工具类实现break和continue
  @Test
  def test8 = {
    breakable{
      for (i <- 1 to 20){
        if (i==5) break
        println(i)
      }
    }
    println("----------------------")
    for(i <- 1 to 20)
    breakable({
      if(i==5) break()
      println(i)
    })
  }
}
